import React, { useState, useEffect } from 'react';
import { Form, Input, Button, DatePicker, Radio, Switch, Space, Select } from 'antd';
import { Contest } from '@/types/contest';
import MDEditor from '@/components/MDEditor';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

interface ContestFormProps {
  initialValues?: Partial<Contest>;
  loading?: boolean;
  onFinish: (values: any) => void;
  onCancel: () => void;
  submitText?: string;
  cancelText?: string;
}

const ContestForm: React.FC<ContestFormProps> = ({
  initialValues,
  loading = false,
  onFinish,
  onCancel,
  submitText = '提交',
  cancelText = '取消',
}) => {
  const [form] = Form.useForm();
  const [contestType, setContestType] = useState('Password Protected'); // 默认为密码保护

  useEffect(() => {
    // 如果是编辑状态，直接使用后台返回的比赛类型
    if (initialValues?.contest_type) {
      setContestType(initialValues.contest_type);
      form.setFieldValue('contest_type', initialValues.contest_type);
    }
  }, [initialValues, form]);

  const handleContestTypeChange = (e: any) => {
    const newType = e.target.value;
    setContestType(newType);
    form.setFieldValue('contest_type', newType);
    // 如果切换为公开比赛，清除密码
    if (newType === 'Public') {
      form.setFieldValue('password', undefined);
    }
  };

  const handleSubmit = (values: any) => {
    const [startTime, endTime] = values.time;
    const formData = {
      ...values,
      start_time: startTime.toISOString(),
      end_time: endTime.toISOString(),
      // 根据比赛类型处理密码
      password: values.contest_type === 'Password Protected' ? values.password : '',
      allowed_ip_ranges: values.allowed_ip_ranges?.split('\n').filter(Boolean) || []
    };

    onFinish(formData);
  };

  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={handleSubmit}
      initialValues={{
        title: initialValues?.title || '',
        description: initialValues?.description || '',
        time: initialValues ? 
          [dayjs(initialValues.start_time), dayjs(initialValues.end_time)] : 
          [dayjs(), dayjs().add(2, 'hour')],
        rule_type: initialValues?.rule_type || 'ACM',
        contest_type: contestType,
        password: initialValues?.password || '',
        real_time_rank: initialValues?.real_time_rank !== undefined ? initialValues.real_time_rank : true,
        visible: initialValues?.visible !== undefined ? initialValues.visible : true,
        allowed_ip_ranges: initialValues?.allowed_ip_ranges?.join('\n') || ''
      }}
    >
      <Form.Item
        name="title"
        label="比赛标题"
        rules={[{ required: true, message: '请输入比赛标题' }]}
      >
        <Input placeholder="请输入比赛标题" />
      </Form.Item>

      <Form.Item
        name="time"
        label="比赛时间"
        rules={[{ required: true, message: '请选择比赛时间' }]}
      >
        <RangePicker 
          showTime 
          format="YYYY-MM-DD HH:mm:ss" 
          style={{ width: '100%' }}
        />
      </Form.Item>

      <Form.Item
        name="rule_type"
        label="规则类型"
        rules={[{ required: true, message: '请选择规则类型' }]}
      >
        <Select>
          <Option value="ACM">ACM</Option>
          <Option value="OI">OI</Option>
        </Select>
      </Form.Item>

      <Form.Item
        name="contest_type"
        label="比赛类型"
        rules={[{ required: true, message: '请选择比赛类型' }]}
      >
        <Radio.Group onChange={handleContestTypeChange}>
          <Radio value="Public">公开比赛</Radio>
          <Radio value="Password Protected">密码保护</Radio>
        </Radio.Group>
      </Form.Item>

      {contestType === 'Password Protected' && (
        <Form.Item
          name="password"
          label="比赛密码"
          rules={[{ required: true, message: '请输入比赛密码' }]}
        >
          <Input.Password placeholder="请输入比赛密码" />
        </Form.Item>
      )}

      <Form.Item
        name="real_time_rank"
        label="实时排名"
        valuePropName="checked"
      >
        <Switch />
      </Form.Item>

      <Form.Item
        name="visible"
        label="是否公开"
        valuePropName="checked"
        tooltip="设置比赛是否在列表中显示，不影响比赛类型"
      >
        <Switch />
      </Form.Item>

      <Form.Item
        name="allowed_ip_ranges"
        label="允许的IP范围"
        tooltip="每行一个IP范围，例如：192.168.1.0/24"
      >
        <Input.TextArea rows={4} placeholder="每行一个IP范围" />
      </Form.Item>

      <Form.Item
        name="description"
        label="比赛描述"
      >
        <MDEditor />
      </Form.Item>

      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit" loading={loading}>
            {submitText}
          </Button>
          <Button onClick={onCancel}>
            {cancelText}
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default ContestForm; 